package com.iss.yunpan.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.iss.yunpan.entity.FileContent;
import com.iss.yunpan.service.FileService;
import com.sun.xml.internal.ws.policy.privateutil.PolicyUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.bind.support.SessionStatus;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class FileController {
    @Autowired
    private FileService service;
    @RequestMapping("getAllFile")
    @ResponseBody
    public Map<String,Object> getAllFile(String id,int page,int limit,String parentId){
        System.out.println(id);
        if(parentId==null){
            parentId="0";
        }
        Map<String,Object> map=new HashMap<>();
        PageHelper.startPage(page,limit);
        List<FileContent> list=service.getAllFile(id,parentId);
        PageInfo<FileContent> pageInfo= new PageInfo<>(list);
        System.out.println(pageInfo);
        map.put("code",0);
        map.put("msg","");
        map.put("patentId",parentId);
        map.put("count",pageInfo.getTotal());
        map.put("data",pageInfo.getList());
        return map;
    }
    @RequestMapping("uploadFile")
    @ResponseBody
    public Map<String,Object> uploadFile(@RequestParam("file") MultipartFile file,String parentId) throws IOException {
        Map<String, Object> map = new HashMap<>();
        if(parentId==null){
            parentId="0";
        }
        if (file != null) {
            String fileName = file.getOriginalFilename();
            InputStream input = file.getInputStream();
            service.uploadFile(fileName,input, parentId);
            map.put("code", 0);
            map.put("msg", "上传成功");
        } else{
            map.put("msg", "文件不能为空");
        }
        return map;
    }
    @RequestMapping("insertFloder")
    @ResponseBody
    public Map<String,Object> insertFloder(String fileName,Integer parentId){
        Map<String, Object> map = new HashMap<>();
        if(parentId==null){
            parentId=0;
        }
        if(fileName.equals("")){
            map.put("msg","文件夹不能为空");
        }else {
            boolean flag= service.checkFileContent(fileName,parentId);
            if(flag)
                map.put("msg","文件夹名字不能重复");
            else{
                service.insertFloder(fileName,parentId);
                map.put("code",0);
                map.put("msg","文件夹新建成功");
            }
        }
        return map;
    }
    @ResponseBody
    @RequestMapping("download")
    public ResponseEntity<byte[]> download(String fileAbsolute, HttpServletRequest request, HttpServletResponse response)throws IOException {
        String downLoadPath = request.getServletContext().getRealPath("uploadfiles");
        // 设置下载文件使用的报头
        response.setHeader("Content-Type", "application/x-msdownload");
        response.setHeader("Content-Disposition", "attachment; filename=" + toUTF8String(fileAbsolute));
        byte[] newByte = service.download(fileAbsolute);
        return new ResponseEntity<byte[]>(newByte, HttpStatus.OK);
    }

    /**
     * 下载保存时中文文件名的字符编码转换方法
     */
    public String toUTF8String(String str)
    {
        StringBuffer sb = new StringBuffer();
        int len = str.length();
        for (int i = 0; i < len; i++) {
            // 取出字符中的每个字符
            char c = str.charAt(i);
            // Unicode 码值为 0 ～ 255 时，不做处理
            if (c >= 0 && c <= 255) {
                sb.append(c);
            } else {
                // 转换 UTF-8 编码
                byte b[];
                try {
                    b = Character.toString(c).getBytes("UTF-8");
                } catch (Exception e) {
                    e.printStackTrace();
                    b = null;
                }
                // 转换为%HH的字符串形式
                for (int j = 0; j < b.length; j++) {
                    int k = b[j];
                    if (k < 0) {
                        k &= 255;
                    }
                    sb.append("%" + Integer.toHexString(k).toUpperCase());
                }
            }
        }
        return sb.toString();
    }
}